package fun.wlfj.servlet;

import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.net.HttpCookie;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fun.wlfj.vo.VoteTask;

/**
 * Servlet implementation class indexservlet
 */
@WebServlet("/indexservlet")
public class indexservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private boolean isFirstTime = true;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public indexservlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public void init() throws ServletException {
    	//我们将所有的session手动失效
    	
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(isFirstTime) {
			isFirstTime = false;
			request.getSession().invalidate();
		}
		// TODO Auto-generated method stub
		// 现在我们需要判断当前用户的cookies(暂时不实现)我们需要将当前用户的数据放上来 如果没有则跳到提示页面
		@SuppressWarnings("unchecked")
		LinkedList<VoteTask> taskList = (LinkedList<VoteTask>)this.getServletContext().getAttribute("TaskList");
		if(taskList == null){
			taskList = new LinkedList<VoteTask>();
			this.getServletContext().setAttribute("TaskList", taskList);
		}
		
		VoteTask currentTask = new VoteTask();
		if(!taskList.isEmpty())
			currentTask = taskList.getLast();
		int currentVoteID = -1;
		Object t = null;
		if((t = request.getSession().getAttribute("CurrentVoteID")) != null) {
			currentVoteID = (Integer)t;
		}
		if(currentTask.getVoteID() == -1 || currentTask.isFinished() || currentVoteID == currentTask.getVoteID()) {
			// 当前列表为空 投票任务结束 已经投过票了
			request.setAttribute("message", "当前暂无投票任务.");
			request.getRequestDispatcher("finished.jsp").forward(request, response);
		}else {
			// 有任务 我们将数据放在request中
			// 将任务vo直接放进去 其他的不用
			request.setAttribute("VoteTask", currentTask);
			request.getRequestDispatcher("vote.jsp").forward(request, response);
		}
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
